package com.bobo.myapplication.utils;

import android.content.Context;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Created by ZJB on 2018/1/11.
 *
 * @ copyright: iwhere chengdu technology
 */

public class ToastUitl {
    final String TAG  = ToastUitl.class.getSimpleName();

    private static ToastUitl sInstance;
    private Toast mToast;
    private View contentView;

    private ToastUitl(){
    }
    public static ToastUitl getInstance(){
        if(sInstance==null){
            synchronized(ToastUitl.class){
                if(sInstance==null){
                    sInstance=new ToastUitl();
                }
            }
        }
        return sInstance;
    }

    //使用的时候需要先初始化，最好是在appliction中初始化
    public void initToastUtil(@NonNull Context context){
        if(mToast == null){
            mToast = new Toast(context);
        }
    }



    public ToastUitl setContentView(View contentView) {
        this.contentView = contentView;
        return this;
    }

    public ToastUitl setText(@IdRes int tvId,String text){
        if(contentView != null){
            TextView textView = contentView.findViewById(tvId);
            if(textView == null){
                Log.w(TAG, "setText: 找不到textview:"+tvId );
            }else {
                textView.setText(text);
            }
        }else {
            Log.w(TAG, "setText: 请先设置contentView" );
        }
        return this;
    }



    public void showViewShort(){
        checkToastNull();
        checkContentViewNull();
        mToast.setDuration(Toast.LENGTH_SHORT);
        mToast.setView(contentView);
        mToast.show();
    }

    public ToastUitl setGravity(int gravity){
        checkToastNull();
        mToast.setGravity(gravity,0,0);
        return this;
    }

    private void checkToastNull(){
        if(mToast == null){
            throw  new NullPointerException("请初始化此方法ToastUitl.initToastUtil()");
        }
    }


    private void checkContentViewNull(){
        if(mToast == null){
            throw  new NullPointerException("请在此之前设置ContentView");
        }
    }


}
